package site.kitcheng.springboottest.test;

/**
 * ClassName: KeyConverter
 * Package: site.kitcheng.springboottest.test
 * Description:
 *
 * @Author jiangCheng
 * @Create 2025/2/24 11:04
 * @Version 1.0
 */
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class KeyConverter {

    // 从 Base64 字符串恢复公钥
    public static PublicKey getPublicKeyFromBase64(String base64PublicKey) throws Exception {
        byte[] decodedKey = Base64.getDecoder().decode(base64PublicKey);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");  // 使用 RSA 算法
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
        return keyFactory.generatePublic(keySpec);
    }

    // 从 Base64 字符串恢复私钥
    public static PrivateKey getPrivateKeyFromBase64(String base64PrivateKey) throws Exception {
        byte[] decodedKey = Base64.getDecoder().decode(base64PrivateKey);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");  // 使用 RSA 算法
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
        return keyFactory.generatePrivate(keySpec);
    }

    public static void main(String[] args) throws Exception {
        // 假设这是 Base64 编码的公钥和私钥
        String base64PublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAv+e15r6NZs6Z+s3JhGuPLqeIGrdx+a5NtDISVZDEqfv9TEpcOABDMELcF2worJ5h966iM/eNFcq5ci+Lxuhr5uG0D2R56vjTw1wcMHw6pLkKI7fZM3bA9Oatqx/t5mp0KU7NJhnLWCUSEwpdXe8sDNiVZmhiJG+kRp4nrHEIYE8Y6f0KmjdfiNG9nDwY7540lksntDLXknM3LmT2SlVzw65lWK6O1RYVBAlNfTyTZCoidSIOQwSh8tHmzKP/VO0XB0iacDtoqY+JgU+s/G+cby/iSWKbJFpEUaOHslh7wKHsKFZLCoBKJkTFSvQ3W7ggVV25jd+8XNVdSxcl8DpPCwIDAQAB";
        String base64PrivateKey = "MIIEvQIBADAN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8QKBgQCH6jZWWkrWig54oK+3AJyoP9udWIB8ALNzgWByVbjkK+2XVkFSrw8JcNnk4XBUVX4C9kgtYlwEcsxgzrvIAlsL966E1vO4uEPNzoMHbqk+cxYEkQ6zGpdXg7IMs8Ox2pMmhXrpc6RBsLxYoT1TpR17/HwZYvL5VnkQRfrerw6/8wKBgH6ICIWYjP0fvjEw5AroUqzaQNKoWnH9A4su/RHP5zwTf6UXHk4pGrC6yIdiMppGgvWm4UysMU5VBE+JG1YfCxR31zUnqMMKhMr+fltcacSqUpsGR6NSx8i2JRCSWkWknizZ5aUNoV3dNyVTXWt4ryjCvmp6v+AVF5IBCI65uhMRAoGAT8xs0CgsroopQVoCwgeayD3ej+dBOSknxIUtdCBzM7B/5HwiVQp7oqTI488tCf3q2+7GQvx9fWycerBxUiP+OkyHnSMxmd2HH8NeP+g0//kofBNhRjmmWiqCjvwOLW6kjlajJuD9fw1TE49auEH865+k0BklB+JWdXMxyg1nN9Q=" ;

        // 从 Base64 恢复公钥
        PublicKey publicKey = getPublicKeyFromBase64(base64PublicKey);
        System.out.println("Recovered Public Key: " + publicKey);

        // 从 Base64 恢复私钥
        PrivateKey privateKey = getPrivateKeyFromBase64(base64PrivateKey);
        System.out.println("Recovered Private Key: " + privateKey);
    }
}

